package app.test.com.beginner.server;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.annotation.IntDef;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.widget.RemoteViews;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import app.test.com.beginner.R;
import app.test.com.beginner.tools.TrafficBean;
import app.test.com.beginner.util.Tools;

/**
 * 作者：韩笑 on 2017-08-12 13:52
 * <p>
 * 作用：工具服务
 */


public class ToolsServer extends Service {
    private static final String TAG = ToolsServer.class.getSimpleName();
    private static final int REQUEST_CODE = 100;
    private static final String ACTION_PLAY = "close";
    private Notification notification;
    private Context context = this;
    private TrafficBean trafficBean;
    private FuckReceiver player;
    private Tools tools;
    private boolean isClose = false;
    /**
     * 获取网速
     */
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (!isClose){
                switch (msg.what) {
                    case 1:
                        notification.contentView.setTextViewText(R.id.wangsu, "网速:" + msg.obj + "kb/s");
                        NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
                        mNotificationManager.notify(110, notification);
                        break;
                    case 2:
                        getPing();
                        handler.sendEmptyMessageDelayed(2, 1000);
                        break;
                    default:

                        break;
                }
            }

            super.handleMessage(msg);
        }
    };

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    /**
     * 首次进入服务调用方法
     */
    @Override
    public void onCreate() {
        super.onCreate();
        tools = new Tools();
        player = new FuckReceiver();
        IntentFilter mFilter = new IntentFilter();
        mFilter.addAction("close");
        registerReceiver(player, mFilter);
        createServer();
    }

    /**
     * 创建前台服务
     */
    private void createServer() {
        Intent intentPlay = new Intent(ACTION_PLAY);
        RemoteViews remoteViews = new RemoteViews(this.getPackageName(), R.layout.activity_main);// 获取remoteViews（参数一：包名；参数二：布局资源）
        PendingIntent pIntentPlay = PendingIntent.getBroadcast(this.getApplicationContext(),
                REQUEST_CODE, intentPlay, PendingIntent.FLAG_UPDATE_CURRENT);
        remoteViews.setOnClickPendingIntent(R.id.guanbi, pIntentPlay);
        Notification.Builder builder = new Notification.Builder(this.getApplicationContext())
                .setContent(remoteViews);// 设置自定义的Notification内容
        builder.setWhen(System.currentTimeMillis()).setSmallIcon(R.drawable.ip);
        notification = builder.getNotification();// 获取构建好的通知--.build()最低要求在// API16及以上版本上使用，低版本上可以使用.getNotification()。
        startForeground(110, notification);// 开始前台服务
        updateServer(tools.getIPAddress(context));
        handler.sendEmptyMessageDelayed(2, 1000);

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        String arg = intent.getStringExtra("close");
        //这里有问题  还要改改
        if (!TextUtils.isEmpty(arg)) {
            isClose = true;
            stopForeground(true);// 停止前台服务--参数：表示是否移除之前的通知
            stopSelf();
        }
        return super.onStartCommand(intent, flags, startId);
    }

    /**
     * 更新前台ui
     *
     * @param arg
     */
    private void updateServer(String arg) {
        notification.contentView.setTextViewText(R.id.xianshi, "手机ip:" + arg);
        trafficBean = new TrafficBean(this, handler, 12580);
        trafficBean.startCalculateNetSpeed();
        NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        mNotificationManager.notify(110, notification);
    }

    @Override
    public void onDestroy() {
        stopForeground(true);// 停止前台服务--参数：表示是否移除之前的通知
        if (player != null) {
            unregisterReceiver(player);// 解除广播注册
        }
        super.onDestroy();
    }

    public void getPing() {
        try {
            String lost = new String();
            String delay = new String();
            Process p = null;
            p = Runtime.getRuntime().exec("ping -c 1 " + "223.5.5.5");
            BufferedReader buf = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String str = new String();
            while ((str = buf.readLine()) != null) {
                if (str.contains("packet loss")) {
                    int i = str.indexOf("received");
                    int j = str.indexOf("%");
                    Log.d(TAG, "丢包率:" + str.substring(i + 10, j + 1));
                    lost = str.substring(i + 10, j + 1);
                }
                if (str.contains("avg")) {
                    int i = str.indexOf("/", 20);
                    int j = str.indexOf(".", i);
                    Log.d(TAG, "延迟:" + str.substring(i + 1, j));
                    delay = str.substring(i + 1, j);
                    delay = delay + "ms";
                }
            }
            if (delay.equals("")) {
                delay = "@!#!@";
                lost = "!@#!@";
            }
            notification.contentView.setTextViewText(R.id.diubao, lost);
            notification.contentView.setTextViewText(R.id.yanchi, delay);
            notification.contentView.setTextViewText(R.id.xianshi, "手机ip:" + tools.getIPAddress(context));
            NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            mNotificationManager.notify(110, notification);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
